package com.centriole.service.workflow.util;

import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * http工具
 */
public class HttpUtil {
    public static final String POST = "POST";
    public static final String GET = "GET";

    public static final int TIMEOUT_30S = 30000;

    public static String http(String urlStr, String method, String postData, int timeout) {
        byte tmpByte = 0;
        URL url = null;
        HttpURLConnection httpConn = null;
        InputStream inputStream = null;
        String responseText = null;
        try {

            url = new URL(urlStr);
            httpConn = (HttpURLConnection) url.openConnection();

            HttpURLConnection.setFollowRedirects(true);
            httpConn.setRequestMethod(method);
            httpConn.setRequestProperty("content-type", "text/html");
            httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");
            httpConn.setReadTimeout(timeout);
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);

            if (postData != null) {
                OutputStreamWriter out = new OutputStreamWriter(httpConn.getOutputStream(), "utf-8");
                out.write(postData);
                out.flush();
                out.close();
            }

            inputStream = httpConn.getInputStream();
            List<Byte> tmpStream = new ArrayList<Byte>();
            while ((tmpByte = (byte) inputStream.read()) != -1) {
                tmpStream.add(tmpByte);
            }
            inputStream.close();
            httpConn.disconnect();
            responseText = new String(toByteArray(tmpStream), "utf-8");

        } catch (MalformedURLException e) {
        } catch (IOException e) {
        } catch (Exception e) {
        }
        return responseText;
    }

    public static String postMethod(String url, HashMap<String, String> hm, int timeout) throws IOException {
        HttpClient httpClient = new HttpClient();
        //httpClient.getHostConfiguration().setHost(host, port, "http");
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);

        PostMethod post = new PostMethod(url);
        post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

        NameValuePair[] param = new NameValuePair[hm.size()];
        byte i = 0;
        for (String key : hm.keySet()) {
            param[i++] = new NameValuePair(key, hm.get(key));
        }
        post.setRequestBody(param);
        post.releaseConnection();

        httpClient.executeMethod(post);

        InputStream inputStream = post.getResponseBodyAsStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
        StringBuffer stringBuffer = new StringBuffer();
        String str= "";
        while((str = br.readLine()) != null){
            stringBuffer .append(str );
        }
        br.close();
        inputStream.close();
        return stringBuffer.toString();
    }

    private static byte[] toByteArray(List<Byte> byteList) {
        int index = byteList.size();
        if (index > 0) {
            byte[] bytes = new byte[index];
            for (int i = 0; i < index; i++) {
                bytes[i] = byteList.get(i);
            }
            return bytes;
        } else {
            return null;
        }
    }
    
    
    /**
     * 发送GET请求并将结果封装成Map集合
     * @param url		接口URL
     * @return	Map< String , Object >
     */
    @SuppressWarnings("unchecked")
	public static Map<String, Object> getToMap(String url){
    	Map<String, Object> params = new HashMap<>();
    	String httpResponseBody = http(url, "GET", null, 3000);
    	JSONObject httpResponseBodyJson = JSONObject.fromObject(httpResponseBody);
    	httpResponseBodyJson.keySet().parallelStream().forEach(e->{
    		params.put(e.toString(), httpResponseBodyJson.get(e.toString()));
    	});
    	return params;
    }
    
    public static void main(String[] args) throws IOException {
    //	System.out.println(HttpUtil.http("http://192.168.1.166:7777/test/sayHello", "GET", null, 3000));
    	getToMap("http://192.168.1.166:7777/test/getResult").entrySet().parallelStream().forEach(System.out::println);
    }

}
